import logging
from logging.handlers import TimedRotatingFileHandler
from common.com_conf import Conf
import os
import traceback


def init():
    logging.basicConfig(level=Conf.yaml["dpb"]["basic"]["django"]["logger"]["level"],
                        format=Conf.yaml["dpb"]["basic"]["django"]["logger"]["format"])
    logging.getLogger().setLevel(Conf.yaml["dpb"]["basic"]["django"]["logger"]["level"])
    logger_info = logging.getLogger(f'{Conf.yaml["dpb"]["basic"]["django"]["logger"]["name"]}-info')
    logger_error = logging.getLogger(f'{Conf.yaml["dpb"]["basic"]["django"]["logger"]["name"]}-error')

    log_path = Conf.yaml["dpb"]["basic"]["django"]["logger"]["path"]

    if len(log_path) > 0:
        if not os.path.exists(log_path):
            os.makedirs(log_path)
        if not log_path.endswith(os.sep):
            log_path = f"{log_path}{os.sep}"

    info_handler = TimedRotatingFileHandler(
        encoding="utf8",
        filename=f'{log_path}/{Conf.yaml["dpb"]["basic"]["django"]["logger"]["name"]}-info.log',
        when=Conf.yaml["dpb"]["basic"]["django"]["logger"]["roating_when"],
        interval=Conf.yaml["dpb"]["basic"]["django"]["logger"]["roating_interval"],
        backupCount=Conf.yaml["dpb"]["basic"]["django"]["logger"]["roating_count"])
    info_handler.setFormatter(logging.Formatter(Conf.yaml["dpb"]["basic"]["django"]["logger"]["format"]))

    error_handler = TimedRotatingFileHandler(
        encoding="utf8",
        filename=f'{log_path}/{Conf.yaml["dpb"]["basic"]["django"]["logger"]["name"]}-error.log',
        when=Conf.yaml["dpb"]["basic"]["django"]["logger"]["roating_when"],
        interval=Conf.yaml["dpb"]["basic"]["django"]["logger"]["roating_interval"],
        backupCount=Conf.yaml["dpb"]["basic"]["django"]["logger"]["roating_count"])
    error_handler.setFormatter(logging.Formatter(Conf.yaml["dpb"]["basic"]["django"]["logger"]["format"]))

    logger_info.addHandler(info_handler)
    logger_error.addHandler(error_handler)

    return logger_info, logger_error


class Log:
    __logger_info, __logger_error = init()

    @classmethod
    def info(cls, msg: str):
        cls.__logger_info.info(msg, stacklevel=2)

    @classmethod
    def error(cls, msg: str, ex: bool = True):
        # 告警并记日志(报警等待接口)
        if ex:
            cls.__logger_error.error(f'{msg}\n{traceback.format_exc()}', stacklevel=2)
        else:
            cls.__logger_error.error(msg, stacklevel=2)
